package org.cypress.rtpack.controller;
//处理rtpack_hostname这个表的控制器

import org.cypress.rtpack.VO.SimRep;
import org.cypress.rtpack.common.core.Result;
import org.cypress.rtpack.entity.RtpackHostname;
import org.cypress.rtpack.service.IRtpackHostnameService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/rtpack_hostname")
public class RtpackHostnameController {

    @Autowired
    private IRtpackHostnameService rtpackHostnameService;

    private static final Logger logger = LoggerFactory.getLogger(RtpackHostnameController.class);

    @GetMapping("/by_index/{index}")
    public Result<RtpackHostname> getByIndex(@PathVariable("index") Integer index) {
        RtpackHostname inst = rtpackHostnameService.getByIndex(index);
        return Result.dataOf(inst);
    }




    // 允许所有来源访问此接口
    @CrossOrigin
    @GetMapping("/tell_me_position")
    public Result<SimRep> getClientPosition(HttpServletRequest request) {
        String ipAddress = request.getRemoteAddr();
        RtpackHostname rtpackHostname = rtpackHostnameService.getByIP(ipAddress);
        if(rtpackHostname == null) {
            rtpackHostname = new RtpackHostname();
            rtpackHostname.setIndex(0);
            rtpackHostname.setIP(ipAddress);
            rtpackHostname.setHostname(ipAddress);
        }
        return Result.dataOf(rtpackHostname);
    }

    @GetMapping("/list")
    public Result<RtpackHostname> getList() {
        List<RtpackHostname> list = rtpackHostnameService.getAll();
        return Result.dataOf(list);
    }

    @PutMapping("/updateByIndex")
    public Result<RtpackHostname> updateConfig(@RequestBody RtpackHostname inst) {
        RtpackHostname updatedInst = rtpackHostnameService.updateByIndex(inst);
        return Result.dataOf(updatedInst);
    }

    @PutMapping("/batchUpdateByIndex")
    public Result<List<RtpackHostname>> batchUpdate(@RequestBody List<RtpackHostname> instList) {
        List<RtpackHostname> updated = rtpackHostnameService.batchUpdateByIndex(instList);
        return Result.dataOf(updated);
    }

    /**
     * 删除原表并重新插入数据
     * @param instList 要插入的新数据列表
     * @return 操作结果（包含插入后的数据列表）
     */
    @PostMapping("/replaceAll")
    public Result<List<RtpackHostname>> replaceAll(@RequestBody List<RtpackHostname> instList) {
        try {
            // 1. 清空原表
            rtpackHostnameService.deleteAllRecords();
            // 2. 批量插入新数据
            List<RtpackHostname> insertedList = rtpackHostnameService.batchInsert(instList);

            return Result.dataOf(insertedList);
        } catch (Exception e) {
            return new Result<>(Result.FAIL_CODE, "数据替换失败: " + e.getMessage());
        }
    }
}
